// import _ from 'underscore'

const PostTag = require('./models.js')
const shortid = require('shortid')
const Util = require('../utils/util.js')

let checkTagFields = (formData, req) => {
  // 管理员用户以上权限才可以创建标签
  // let hasLogin = req.session.userLogined
  // let userInfo = req.session.userInfo

  // if (!hasLogin || (userInfo.role !== 'super' && userInfo.role !== 'admin')) {
  //   return false
  // }

  let { name, alias, cover, enable } = formData
  if (name.length <= 0 || name.length > 20) {
    return false
  } else if (!/^[a-zA-Z0-9_-]{1,20}$/.test(alias)) {
    return false
  } else if (cover.length > 200) {
    return false
  }
  return true
}

module.exports = {
  /**
   * 创建标签
   * @param {*} req 
   * @param {*} res 
   * @param {*} next 
   */
  async createOne(req, res, next) {
    // 校验传入的参数
    let fields = req.body
    try {
      let validateResult = checkTagFields(fields, req)
      if (!validateResult) {
        return res.status(500).send(Util.renderApiErr(req, res, 500, '数据校验失败'))
      }
    } catch (err) {
      return res.status(500).send(Util.renderApiErr(req, res, 500, err))
    }

    const obj = {
      name: fields.name,
      alias: fields.alias,
      description: fields.description,
      cover: fields.cover,
      group:Util.checkGroupId(fields.group),
      enable: fields.enable ? true : false
    }

    const newTag = new PostTag(obj)

    try {
      let tagObj = await newTag.save()
      return res.send(Util.renderApiData(req, res, 200, '标签创建成功', { id: tagObj._id }))
    } catch (err) {
      return res.status(500).send(Util.renderApiErr(req, res, 500, err))
    }
  },

  /**
  * 修改标签列表
  */
  async updateOne(req, res, next){
    // 校验传入的参数
    let fields = req.body
    try {
      let validateResult = checkTagFields(fields, req)
      if (!validateResult) {
        return res.status(500).send(Util.renderApiErr(req, res, 500, '数据校验失败'))
      }
    } catch (err) {
      return res.status(500).send(Util.renderApiErr(req, res, 500, err))
    }

    const obj = {
      name: fields.name,
      alias: fields.alias,
      description: fields.description,
      cover: fields.cover,
      group: Util.checkGroupId(fields.group),
      enable: fields.enable ? true : false
    }

    try {
      let item_id = fields._id
      await PostTag.findOneAndUpdate({ _id: item_id }, { $set: obj })
      return res.send(Util.renderApiData(req, res, 200, '标签修改成功', { id: item_id }))
    } catch (err) {
      return res.status(500).send(Util.renderApiErr(req, res, 500, err))
    }
  },

  /**
  * 获取标签对象
  * @param tagName
  * @param tagId
  */
  async getTag(req, res, next){
    // 校验传入的参数
    let fields = req.query;
    let tagName = fields.tagName;
    if(!tagName){
      return res.status(500).send(Util.renderApiErr(req, res, 500, '没有找到tagName'));
    }

    try {
      let targetTag = await PostTag.findOne({ name: tagName })
      let obj = {
        tag:targetTag
      }
      
      return res.send(Util.renderApiData(req, res, 200, '标签获取成功', obj))
    } catch (err) {
      return res.status(500).send(Util.renderApiErr(req, res, 500, err))
    }
  },

  /**
   * 获取标签列表
   * @param {*} req 
   * @param {*} res 
   * @param {*} next 
   */
  async getList(req, res, next) {
    try {
      // Util.log(req.query)
      let fields = req.query
      let queryObj = {
        group:fields.group
      }
      // let page = Number(fields.page) || 1
      // let mode = fields.mode  // 模式 full/simple
      // let pageSize = Number(fields.pageSize) || Number(fields.limit) || 10
      // let isHot = fields.isHot
      // 抽取属性字段作为key |alias
      // let array = fields.array

      // 排序
      let sortObj = { data: -1 }
      // if (isHot) {
      //   sortObj = { clicks: -1 }
      // }

      // if (mode === 'full') {
      //   page = 1
      //   pageSize = 1000
      // }

      // 查询文档
      // let tagList = await PostTag.find(queryObj).sort(sortObj).skip((page - 1) * pageSize).limit(pageSize).exec()
      let tagList = await PostTag.find(queryObj).sort(sortObj).exec()
      const totalCounts = await PostTag.count(queryObj)
      // Util.log(tagList, totalCounts)
      // if(array){
      //   tagList = _.groupBy(tagList, array)
      //   //按照key alias排序
      //   const ordered = {};
      //   Object.keys(tagList).sort().forEach(function(key) {
      //     ordered[key] = tagList[key];
      //   });
      //   tagList = ordered;
      // }

      let tagObj = {
        list: tagList,
        // page: page,
        // lastPage: Math.ceil(totalCounts / pageSize),
        // pageSize: pageSize,
        totalCounts: totalCounts
      }
      return res.send(Util.renderApiData(req, res, 200, '标签列表获取成功', tagObj))
    } catch (err) {
      return res.status(500).send(Util.renderApiErr(req, res, 500, err))
    }
  },

  /**
   * 删除一个标签
   * @param {*} req 
   * @param {*} res 
   * @param {*} next 
   */
  async deleteOne(req, res, next) {
    try {
      // let userInfo = req.session.userInfo
      let errMsg = ''
      let id = req.body._id
      Util.log(id)
      if (!shortid.isValid(id)) {
        errMsg = 'ID格式校验失败'
      }

      // if (userInfo.role !== 'super' && userInfo.role !== 'admin') {
      //   errMsg = '没有操作权限'
      // }

      if (errMsg) {
        return res.status(500).send(Util.renderApiErr(req, res, 500, errMsg))
      }

      await PostTag.remove({ _id: id })
      return res.send(Util.renderApiData(req, res, 200, '删除成功', {}))
    } catch (err) {
      return res.status(500).send(Util.renderApiErr(req, res, 500, err))
    }
  }
}